import subprocess
import threading
from queue import Queue
from .tool import Tool


class ToolExecutor:
    def __init__(self, log_queue: Queue):
        self.log_queue = log_queue
        self.processes = {}

    def execute(self, tool: Tool):
        def run():
            try:
                proc = subprocess.Popen(
                    tool.command,
                    shell=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT,
                    text=True
                )
                self.processes[tool.name] = proc
                tool.status = "running"

                while True:
                    output = proc.stdout.readline()
                    if output == '' and proc.poll() is not None:
                        break
                    if output:
                        self.log_queue.put(f"[{tool.name}] {output.strip()}")

                exit_code = proc.poll()
                if exit_code == 0:
                    tool.status = "stopped"
                else:
                    tool.status = "error"

            except Exception as e:
                self.log_queue.put(f"[ERROR] {tool.name} 执行失败: {str(e)}")
                tool.status = "error"

        threading.Thread(target=run, daemon=True).start()